#include "timerservice.h"

TimerService::TimerService(QObject *parent) : QObject(parent)
{
    syncTimerId=0;
}

void TimerService::updateTask()
{
    QSettings reg(REG_APP,QSettings::NativeFormat);
    QStringList taskList=reg.childGroups();
    if(taskList.isEmpty())
    {
        appendLog("Sync Finished, Item Count 0");
        return;
    }

    appendLog(QString("Sync Finished, Item Count %1").arg(taskList.size()));
    foreach (QString item, taskList) {
        processTask(item);
    }
}

void TimerService::setTaskStruct(const QString &uid,
                                 const QString &key,
                                 QVariant value)
{
    QSettings reg(REG_APP,QSettings::NativeFormat);
    reg.beginGroup(uid);
    reg.setValue(key,value);
    reg.endGroup();
}

void TimerService::killAllTimer()
{
    foreach (int id, timerMap.keys()) {
        killTimer(id);
    }
}

void TimerService::processTask(const QString &prefix)
{
    QSettings reg(REG_APP,QSettings::NativeFormat);
    reg.beginGroup(prefix);

    int status=reg.value("status").toInt();
    if(status < 1)
        return;

    QString uid=reg.value("uid").toString();
    int id=reg.value("id").toInt();
    if(timerMap.contains(id) && timerMap.value(id) == uid)
        return;

    QTime time=reg.value("time").toTime();
    QString p_path=reg.value("p_path").toString();
    reg.endGroup();

    taskMap.insert(uid,p_path);

    int offset=QTime::currentTime().secsTo(time);
    if( offset > 0)
    {
        int id=startTimer(offset * 1000);
        setTaskStruct(uid,"id",id);
        setTaskStruct(uid,"status",RT_RUNNING);
        timerMap.insert(id,uid);
    }
}

void TimerService::timerEvent(QTimerEvent *event)
{
    int id=event->timerId();
    if(id == syncTimerId)
        updateTask();
    else
    {
        if(timerMap.contains(id))
        {
            QString uid=timerMap.value(id);
            QString path=taskMap.value(uid);
            QProcess::startDetached(path);

            killTimer(id);
            timerMap.remove(id);
            taskMap.remove(uid);
            setTaskStruct(uid,"status",RT_READY);

            appendLog(QString("%1 executed,Path: %2")
                      .arg(uid)
                      .arg(path));
        }
    }
}

void TimerService::start()
{
    updateTask();
    syncTimerId=startTimer(SYNC_INTERVAL);
}

void TimerService::stop()
{
    killAllTimer();
    killTimer(syncTimerId);
}

void TimerService::appendLog(const QString &event)
{
    QtServiceBase::instance()->logMessage(event);
}
